/* eslint-disable no-confusing-arrow */
/* eslint-disable  no-lonely-if */
import { message } from 'antd';
import { history } from 'umi';
import { get } from 'object-path';
import moment from 'moment/moment';
import BraftEditor from 'braft-editor';
import request from '@/utils/request';
import {
    modifyConfig,
    // modifyItemProps,
    modifyProps
} from '@/pages/Flow/Mine/Apply/utils';
import applyType from '@/pages/Flow/Mine/ApplyPage/consts';
import { dictionaryList } from '@/services/dictionary';
// import styles from './ApplyPage.less';

/**
 * 寻找 fields 里是否存在某个 field字段
 * @param fields
 * @param id
 * @returns {*}
 */
export const existField = (fields, id) => fields.find(item => item.id === id);

const findLabel = (options, valueArr, key = 'id', label = 'departmentName') => {
    if (!valueArr) return [];
    const tmp = [];
    valueArr.reduce((prev, cur) => {
        const findIndex = prev.findIndex(option => option[key] === cur);

        if (findIndex !== -1) {
            tmp.push(prev[findIndex][label]);
        }
        if (prev[findIndex] && prev[findIndex].children) {
            return prev[findIndex].children;
        }
        return prev;
    }, options);

    return tmp;
};

// 详见 src\components\Custom\CustomDatePicker\CustomDatePicker.js
// 获取上下午时间类型的附加参数...增对弹性时间做的修改
export const getTimeExtraParam = (s, e, unit) => {
    if (!s || !e) return {};
    const textMap = {
        am: '上午',
        pm: '下午'
    };
    return unit === 2 ? { startTimeType: textMap[s.dayType], endTimeType: textMap[e.dayType] } : {};
};

/**
 * 获取某个 field 的属性配置
 * @param field
 * @param fields
 * @returns {*}
 */
export const getFieldProps = (field, fields) => {
    if (!fields || fields.length === 0) return {};
    const find = fields.find(item => item.id === field);
    return find.params.component.props;
};

/**
 * 对象 => 对象json字符串
 * @param fields
 * @param form
 * @param duration
 * @param formType
 * @param currentUser
 * @param onlyOnchangeEventField 是否仅获取和流程审批相关的字段
 */
export const getJsonStr = (fields, form, duration, formType, currentUser, onlyOnchangeEventField = false) => {
    const temp = {};

    // 如果是请假类型申请，要提供一个 showTime 以便在详情页显示正确格式，好恶心
    if (formType === applyType.TYPE_LEAVE) {
        const find = fields.find(item => item.id === 'leaveType');
        if (find) {
            const leaveTypeList = get(find, 'params.component.props.data', []);
            const findLeaveType = leaveTypeList.find(item => item.leaveCode === form.getFieldValue('leaveType'));

            if (findLeaveType) {
                temp.formatTime = findLeaveType.leaveUnit;
            } else {
                temp.formatTime = '';
            }
        } else {
            temp.formatTime = '';
        }
    } else if (formType === applyType.TYPE_ON_BUSINESS) {
        // 出差申请按天计算
        temp.formatTime = 2;
    }

    fields.forEach(item => {
        const prop = item.id;
        const value = form.getFieldValue(prop);
        // 判断是否进获取和审批流程有关系的表单字段值
        if (onlyOnchangeEventField) {
            const find = fields.find(newItem => newItem.id === prop && newItem.params && newItem.params.onchangeEvent);
            if (find) {
                if (prop === 'duration') {
                    temp[prop] = duration.durationLong || duration || '';
                } else if (prop === 'newsCnContent' || prop === 'newsEnContent') {
                    temp[prop] = value ? value.toHTML() : '';
                    if (prop === 'newsCnContent') {
                        temp.briefContentCn = value ? value.toText().slice(0, 200) : '';
                    } else if (prop === 'newsEnContent') {
                        temp.briefContentEn = value ? value.toText().slice(0, 200) : '';
                    }
                } else if (prop === 'totalExpense') {
                    temp[prop] = Number(value) || 0;
                } else if (prop === 'startTime' || prop === 'endTime' || prop === 'returnToWork') {
                    // 处理时间
                    if (value && value.time && value.time.isValid()) {
                        // 如果日期和时间分开
                        if (value.timeValue) {
                            temp[prop] = value.time.format(
                                `${moment(value.time, 'YYYY-MM-DD').format('YYYY-MM-DD')} ${value.timeValue}:00`
                            );
                        } else {
                            temp[prop] = value.time.format('YYYY-MM-DD HH:mm:ss');
                        }
                    } else {
                        temp[prop] = '';
                    }
                } else if (item.type === 'custom.LeaveType') {
                    const data = get(item, 'params.component.props.data', []);
                    temp[prop] = value || '';
                    const newFind = data.find(newItem => newItem.leaveCode === value);

                    if (newFind) {
                        temp[`${prop}Name`] = newFind.leaveName;
                    } else {
                        temp[`${prop}Name`] = '';
                    }
                } else if (item.type === 'antd.Checkbox') {
                    // 如果是checkbox，存储布尔值
                    temp[prop] = value;
                } else if (item.type === 'antd.Select') {
                    // 保存下拉框时也要把 name 给后端。。。
                    const data = get(item, 'params.component.props.options', []);
                    const newFind = data.find(newItem => String(newItem.key) === String(value));
                    if (newFind) {
                        if (prop === 'entryPost' || prop === 'recruitPost') {
                            temp[`${prop}Name`] = newFind.postName;
                        } else {
                            temp[`${prop}Name`] = newFind.leaveName;
                        }
                    } else {
                        temp[`${prop}Name`] = '';
                    }
                    temp[prop] = value || '';
                } else if (item.type === 'antd.Radio.Group') {
                    // 保存下拉框时也要把 name 给后端。。。
                    const data = get(item, 'params.component.props.options', []);
                    const newFind = data.find(newItem => newItem.value === value);

                    if (newFind) {
                        temp[`${prop}Name`] = newFind.label;
                    } else {
                        temp[`${prop}Name`] = '';
                    }
                    temp[prop] = value || '';
                } else if (prop === 'demandCompanyId') {
                    temp[prop] = currentUser.companyId;
                    temp[`${prop}Name`] = value;
                } else if (prop === 'companyName') {
                    temp[prop] = value;
                    temp.companyId = currentUser.companyId;
                } else if (prop === 'demandDepartmentId' || prop === 'languageAbility') {
                    const data = get(item, 'params.component.props.options', []);
                    temp[prop] = value || [];
                    temp[`${prop}Name`] = (value || []).map(newItem => {
                        const newFind = data.find(subItem => subItem.value === newItem);

                        if (newFind) {
                            return newFind.label;
                        }
                        return '';
                    });
                } else if (prop === 'releaseTime') {
                    temp[prop] = value && value.time ? value.time.format('YYYY-MM-DD HH:mm:00') : '';
                } else if (prop === 'createTime') {
                    temp[prop] = moment(value).format('YYYY-MM-DD HH:mm:00');
                } else if (
                    prop === 'entryDate' ||
                    prop === 'entryDateEnd' ||
                    prop === 'contractBeginDate' ||
                    prop === 'talentBirth'
                ) {
                    // 处理时间
                    if (value && value.time && value.time.isValid()) {
                        temp[prop] = value.time.format('YYYY-MM-DD');
                    } else {
                        temp[prop] = '';
                    }
                } else if (item.type === 'custom.Editor') {
                    temp[prop] = value.content ? value.content.toHTML() : '';
                } else {
                    if (typeof value === 'number') {
                        temp[prop] = value;
                    } else {
                        temp[prop] = value || '';
                    }
                }
            } else {
                temp[prop] = '';
            }
        } else {
            // 附件传空即可,后端要求附件做特殊处理，不传在原有字段里
            if (prop === 'attachment') {
                temp[prop] = '';
                // 因附件原有字段传空，前端设置必填，所以传个假数据
            } else if (prop === 'attachmentNews' || prop === 'attachmentRec' || prop === 'institutionAttachment') {
                temp[prop] = '1';
            } else if (prop === 'newsCnContent' || prop === 'newsEnContent') {
                temp[prop] = value ? value.toHTML() : '';
                if (prop === 'newsCnContent') {
                    temp.briefContentCn = value ? value.toText().slice(0, 200) : '';
                } else if (prop === 'newsEnContent') {
                    temp.briefContentEn = value ? value.toText().slice(0, 200) : '';
                }
            } else if (prop === 'totalExpense') {
                temp[prop] = Number(value) || 0;
            } else if (prop === 'duration') {
                if (item.params && item.params.onchangeEvent) {
                    temp[prop] = duration.durationLong || duration || 0;
                } else {
                    temp[prop] = duration.durationLong || duration || 0;
                }
            } else if (prop === 'startTime' || prop === 'endTime' || prop === 'returnToWork') {
                // 处理时间
                if (value && value.time && value.time.isValid()) {
                    // 如果日期和时间分开
                    if (value.timeValue) {
                        temp[prop] = value.time.format(
                            `${moment(value.time, 'YYYY-MM-DD').format('YYYY-MM-DD')} ${value.timeValue}:00`
                        );
                    } else {
                        temp[prop] = value.time.format('YYYY-MM-DD HH:mm:ss');
                    }
                } else {
                    temp[prop] = '';
                }
            } else if (item.type === 'custom.LeaveType') {
                const data = get(item, 'params.component.props.data', []);
                temp[prop] = value || '';
                const find = data.find(newItem => newItem.leaveCode === value);

                if (find) {
                    temp[`${prop}Name`] = find.leaveName;
                } else {
                    temp[`${prop}Name`] = '';
                }
            } else if (item.type === 'antd.Checkbox') {
                // 如果是checkbox，存储布尔值
                temp[prop] = value;
            } else if (prop === 'originInstitutionId') {
                // 保存下拉框时也要把 name 给后端。。。
                const data = get(item, 'params.component.props.options', []);
                const find = data.find(newItem => newItem.key === value);
                if (find) {
                    temp.originInstitutionName = find.label;
                } else {
                    temp.originInstitutionName = '';
                }
                temp[prop] = value || '';
            } else if (prop === 'companyName') {
                temp[prop] = value;
                temp.companyId = currentUser.companyId;
            } else if (item.type === 'antd.Select') {
                // 保存下拉框时也要把 name 给后端。。。
                const data = get(item, 'params.component.props.options', []);
                const find = data.find(newItem => newItem.key === value);

                if (find) {
                    temp[`${prop}Name`] = find.label;
                } else {
                    temp[`${prop}Name`] = '';
                }
                temp[prop] = value || '';
            } else if (item.type === 'antd.Radio.Group') {
                // 保存下拉框时也要把 name 给后端。。。
                const data = get(item, 'params.component.props.options', []);
                const find = data.find(newItem => newItem.value === value);

                if (find) {
                    temp[`${prop}Name`] = find.label;
                } else {
                    temp[`${prop}Name`] = '';
                }
                temp[prop] = value || '';
            } else if (prop === 'demandCompanyId') {
                temp[prop] = currentUser.companyId;
                temp[`${prop}Name`] = value;
            } else if (prop === 'demandDepartmentId') {
                const data = get(item, 'params.component.props.options', []);
                temp[prop] = value || [];
                temp[`${prop}Name`] = findLabel(data, value);
            } else if (prop === 'languageAbility') {
                const data = get(item, 'params.component.props.options', []);
                temp[prop] = value || [];
                temp[`${prop}Name`] = findLabel(data, value, 'value', 'label');
            } else if (prop === 'releaseTime') {
                temp[prop] = value && value.time ? value.time.format('YYYY-MM-DD HH:mm:00') : '';
            } else if (prop === 'createTime') {
                temp[prop] = moment(value).format('YYYY-MM-DD HH:mm:00');
            } else if (
                prop === 'entryDate' ||
                prop === 'entryDateEnd' ||
                prop === 'contractBeginDate' ||
                prop === 'talentBirth'
            ) {
                // 处理时间
                if (value && value.time && value.time.isValid()) {
                    temp[prop] = value.time.format('YYYY-MM-DD');
                } else {
                    temp[prop] = '';
                }
            } else if (item.type === 'custom.Editor') {
                temp[prop] = value.content ? value.content.toHTML() : '';
            } else {
                if (typeof value === 'number') {
                    temp[prop] = value;
                } else {
                    temp[prop] = value || '';
                }
            }
        }
    });

    return temp;
};

const getValueByFieldName = (form, fieldName) => {
    const getValue = (name, returnArray = true) => {
        const attachment = form.getFieldValue(name);
        if (!returnArray) return attachment ? attachment.uploadResourceFile : '';
        return attachment && attachment.uploadResourceFile ? [attachment.uploadResourceFile] : [];
    };
    if (Array.isArray(fieldName)) {
        return fieldName.map(name => getValue(name, false)).filter(item => item);
    }
    return getValue(fieldName);
};

// 判断一下是否存在recruitPost这个字段才进行string修改
// 原因在于后端字典里给与的是数字型，而请求接口要求字符串型
const getExtraField = (valueJson, postList) => {
    const getRecruitPostName = recruitPost => {
        const target = postList.find(item => Number(item.id) === Number(recruitPost));
        if (target) {
            return target.postName;
        }
        return '';
    };
    if (valueJson.recruitPost) {
        return {
            recruitPost: String(valueJson.recruitPost),
            recruitPostName: getRecruitPostName(valueJson.recruitPost)
        };
    }
    return {};
};
// 保存申请：至少输入一个必填项
export const handleSubmit = async (
    fields,
    form,
    applicationNo,
    duration,
    formType,
    setSaveLoading,
    params,
    currentUser,
    query,
    domainValue = {},
    postList
) => {
    const values = form.getFieldsValue();
    console.info('values:', fields, values);
    const filledValues = Object.keys(values).filter(prop => {
        const value = values[prop];

        if (prop === 'demandCompanyId' || prop === 'applyDate' || prop === 'createTime') return false;
        if (
            prop === 'startTime' ||
            prop === 'endTime' ||
            prop === 'entryDate' ||
            prop === 'entryDateEnd' ||
            prop === 'contractBeginDate' ||
            prop === 'talentBirth' ||
            prop === 'releaseTime'
        ) {
            return value && value.time;
        }
        if (prop === 'attachmentNews' || prop === 'attachmentRec' || prop === 'institutionAttachment') {
            const attachment = form.getFieldValue(prop);
            return attachment && attachment.allFileList && attachment.allFileList.length > 0;
        }
        if (prop === 'newsCnContent' || prop === 'newsEnContent') {
            return BraftEditor.createEditorState(value).toText() !== '';
        }
        return value;
    });
    const requiredFields = fields.filter(item => item.required).map(item => item.id);
    const find = filledValues.find(item => requiredFields.includes(item));
    // 待发送进来的话不需要判断有没有输入必填项
    if (!find) {
        message.error('您还没有输入，请输入任一必填内容即可保存！');
        return;
    }
    // const attachment = form.getFieldValue('attachment');
    setSaveLoading(true);
    const valueJson = getJsonStr(fields, form, duration, formType, currentUser);
    if (query.talentName) {
        valueJson.talentNameName = query.talentName;
    }
    // 如果是其他原因则保存文本
    // if (valueJson.reason2 === 'supply_for_other') {
    //     valueJson.reason2 = values.otherReason;
    // }

    // 如果新闻，则添加两个附件进去
    let resourceRelationDate = {
        resourceRelation:
            formType === applyType.TYPE_ON_NEWS
                ? getValueByFieldName(form, ['attachmentNews', 'attachmentRec'])
                : getValueByFieldName(form, 'attachment')
    };
    if (formType === applyType.TYPE_ON_SYSTEM) {
        resourceRelationDate = {
            resourceRelation: getValueByFieldName(form, 'institutionAttachment')
        };
    }

    // ------------------------------------------------------- 职级逻辑开始
    const { formValueJson = {} } = domainValue;
    if (formValueJson.id) {
        valueJson.id = formValueJson.id;
    }

    if (query.GRADE_ID) {
        valueJson.id = query.GRADE_ID;
    }

    if (query.GRADE_TYPE_ID) {
        valueJson.rankTypeCode = query.GRADE_TYPE_ID;
        valueJson.companyCode = '随便传的，假装有数据给后端用，否则报错';
    }
    // ------------------------------------------------------- 职级逻辑结束

    valueJson.duration = duration.durationLong || duration;

    const extra = getExtraField(valueJson, postList);
    const formValue = { ...valueJson, ...extra };

    const result = await request('/api/oa/v1/workflow/myprocess/savemyprocessapply', {
        method: 'POST',
        data: {
            ...params,
            formValueJson: JSON.stringify(formValue),
            ...resourceRelationDate
        }
    });

    if (result.code === 10000) {
        message.success('保存成功！');
        history.push({
            pathname: '/personal/portal/flow/mine/myApplication'
        });
    } else {
        message.error(result.msg);
    }
    setSaveLoading(false);
};

// 提交申请
export const submitApply = async (
    e,
    fields,
    form,
    duration,
    formType,
    setLoading,
    params,
    currentUser,
    query,
    domainValue = {},
    postList
) => {
    e.preventDefault();

    form.validateFieldsAndScroll(async (err, values) => {
        const valueJson = getJsonStr(fields, form, duration, formType, currentUser);
        if (query.talentName) {
            valueJson.talentNameName = query.talentName;
        }
        if (!err) {
            setLoading(true);
            // const attachment = form.getFieldValue('attachment');
            // 如果新闻，则添加两个附件进去
            let resourceRelationDate = {
                resourceRelation:
                    formType === applyType.TYPE_ON_NEWS
                        ? getValueByFieldName(form, ['attachmentNews', 'attachmentRec'])
                        : getValueByFieldName(form, 'attachment')
            };
            if (formType === applyType.TYPE_ON_SYSTEM) {
                resourceRelationDate = {
                    resourceRelation: getValueByFieldName(form, 'institutionAttachment')
                };
            }

            // 时间附加参数
            let extraParams = {};
            if (formType === applyType.TYPE_LEAVE || formType === applyType.TYPE_ON_BUSINESS) {
                const extra = {
                    startTime: valueJson.startTime,
                    endTime: valueJson.endTime,
                    flowTimeUnit: valueJson.formatTime
                };

                const { startTime, endTime } = values;
                const timeExtra = getTimeExtraParam(startTime, endTime, valueJson.formatTime);

                extraParams = {
                    businessFormValueJson: JSON.stringify({
                        ...extra,
                        ...timeExtra
                    })
                };

                valueJson.duration = duration.durationLong || duration;
            }

            // ------------------------------------------------------- 职级逻辑开始
            const { formValueJson = {} } = domainValue;
            if (formValueJson.id) {
                valueJson.id = formValueJson.id;
            }

            if (query.GRADE_ID) {
                valueJson.rankCode = query.GRADE_ID;
            }

            if (query.GRADE_TYPE_ID) {
                valueJson.rankTypeCode = query.GRADE_TYPE_ID;
                valueJson.companyCode = '随便传的，假装有数据给后端用，否则报错';
            }
            // ------------------------------------------------------- 职级逻辑结束
            const extra = getExtraField(valueJson, postList);
            const formValue = { ...valueJson, ...extra };
            const result = await request('/api/oa/v1/workflow/myprocess/submitmyprocessapply', {
                method: 'POST',
                data: {
                    ...params,
                    formValueJson: JSON.stringify(formValue),
                    ...resourceRelationDate,
                    ...extraParams
                }
            });

            if (result.code === 10000) {
                message.success('提交成功！');
                history.push({
                    pathname: '/personal/portal/flow/mine/myApplication'
                });
            } else {
                message.error(result.msg);
            }
            setLoading(false);
        }
    });
};

const dateRange = ({
    fields,
    form,
    country,
    formType,
    startTimeName = 'startTime',
    endTimeName = 'endTime',
    disabled = true,
    unit
}) => {
    const existStartTime = existField(fields, startTimeName);
    const existEndTime = existField(fields, endTimeName);
    if (existStartTime) {
        // eslint-disable-next-line no-param-reassign
        fields = modifyConfig(
            startTimeName,
            {
                initialValue: {
                    time: null,
                    unit,
                    country,
                    disabled,
                    type: 'startTime'
                },
                rules: [
                    {
                        validator(_, value, callback) {
                            const endTime = form.getFieldValue(endTimeName);
                            if (!value || !value.time || (value.unit === 2 && !value.dayType)) {
                                callback('请选择开始时间！');
                            } else if (existEndTime && moment(value.time) > moment(endTime.time)) {
                                callback('开始时间不能晚于结束时间！');
                            } else {
                                // 外出、加班不能跨天申请
                                if (formType === applyType.TYPE_OVER_TIME || formType === applyType.TYPE_GO_OUT) {
                                    if (value.time.format('YYYY-MM-DD') !== endTime.time.format('YYYY-MM-DD')) {
                                        callback('不能跨天申请！');
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback();
                                }
                            }

                            form.validateFields([endTimeName]);
                        }
                    }
                ]
            },
            fields
        );
    }
    if (existEndTime) {
        // eslint-disable-next-line no-param-reassign
        fields = modifyConfig(
            endTimeName,
            {
                initialValue: {
                    time: null,
                    unit,
                    country,
                    disabled,
                    type: 'endTime'
                },
                rules: [
                    {
                        validator(_, value, callback) {
                            const startTime = form.getFieldValue(startTimeName);
                            if (!value || !value.time || (value.unit === 2 && !value.dayType)) {
                                callback('请选择结束时间！');
                            } else if (existEndTime && moment(value.time) < moment(startTime.time)) {
                                callback('结束时间不能早于开始时间！');
                            } else {
                                // 外出、加班不能跨天申请
                                if (formType === applyType.TYPE_OVER_TIME || formType === applyType.TYPE_GO_OUT) {
                                    if (value.time.format('YYYY-MM-DD') !== startTime.time.format('YYYY-MM-DD')) {
                                        callback('不能跨天申请！');
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback();
                                }
                            }

                            form.validateFields([startTimeName]);
                        }
                    }
                ]
            },
            fields
        );
    }

    return fields;
};

/**
 * 修改一些默认公共的行为，如：开始时间和结束时间
 * @param json
 * @param country 国家：目前支持 zh 和 sg
 * @param form
 * @param restQuery 查询参数
 * @returns {*|...*[]}
 */
export const initModifyJson = (json, country, form) => {
    let { fields } = { ...json };
    const formType = json.key.split('-')[1];
    // 根据国籍修改上下班时间
    // 厦门：09:00~12:00，13:00~18:00
    // 新加坡：09:00~14:00，14:00~18:00
    // fields = modifyProps(
    //     'startTime',
    //     {
    //         format: 'YYYY-MM-DD',
    //         showTime: country === 'zh' ? { format: 'HH:mm' } : false,
    //         type: country,
    //         amTime: '09:00',
    //         pmTime: country === 'zh' ? '13:00' : '14:00'
    //     },
    //     fields
    // );
    // fields = modifyProps(
    //     'endTime',
    //     {
    //         format: 'YYYY-MM-DD',
    //         showTime: country === 'zh' ? { format: 'HH:mm' } : false,
    //         type: country,
    //         amTime: country === 'zh' ? '12:00' : '14:00',
    //         pmTime: '18:00'
    //     },
    //     fields
    // );

    // 如果是输入框或文本框，则限制输入 2-50 个字符
    fields.forEach(field => {
        if (field.type === 'custom.Editor') {
            fields = modifyConfig(
                field.id,
                {
                    initialValue: BraftEditor.createEditorState(''),
                    rules: [
                        {
                            required: true,
                            validator: (_, value, callback) => {
                                if (!value || value.isEmpty()) {
                                    callback(`请输入${field.name}`);
                                } else {
                                    callback();
                                }
                            }
                        }
                    ]
                },
                fields
            );
        } else if (field.type === 'custom.FileUpload') {
            // 如果附件
            const rules = get(field, 'params.component.config.rules');
            const defaultRules = {
                require: () => ({
                    validator: (value = {}) => !value.allFileList || value.allFileList.length <= 0,
                    msg: `请上传${field.name}`
                }),
                max: len => ({
                    validator: (value = {}) => !value.allFileList || value.allFileList.length > len,
                    msg: `上传文件数不能大于${len}`
                })
            };
            fields = modifyConfig(
                field.id,
                {
                    rules: [
                        ...(rules || []),
                        {
                            validator(_, value, callback) {
                                // 如果必填
                                if (field.required) {
                                    const requiredRule = defaultRules.require();
                                    if (requiredRule.validator(value)) {
                                        callback(requiredRule.msg);
                                    }
                                    if (field.id === 'institutionAttachment') {
                                        const maxRule = defaultRules.max(1);
                                        if (maxRule.validator(value)) {
                                            callback(maxRule.msg);
                                        }
                                    }
                                }
                                // 非必填，但是填了要校验
                                if (formType === applyType.EDIT_SALARY) {
                                    const maxRule = defaultRules.max(10);
                                    if (value && maxRule.validator(value)) {
                                        callback(maxRule.msg);
                                    }
                                }
                                callback();
                            }
                        }
                    ]
                },
                fields
            );
        } else if (
            field.id !== 'salaryStart' &&
            field.id !== 'salaryEnd' &&
            field.id !== 'salaryMonth' &&
            field.id !== 'talentExperience' &&
            field.id !== 'gainPercent' &&
            field.id !== 'companyName'
        ) {
            if (field.type === 'antd.Input') {
                const rules = get(field, 'params.component.config.rules', []);
                if (rules.some(item => item.max || item.min)) {
                    return;
                }
                fields = modifyConfig(
                    field.id,
                    {
                        rules: [
                            ...(rules || []),
                            {
                                validator(_, value, callback) {
                                    if (value) {
                                        if (value.length < 2 || value.length > 50) {
                                            callback('2-50个字符！');
                                        } else {
                                            callback();
                                        }
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ]
                    },
                    fields
                );
            } else if (field.type === 'antd.Input.TextArea') {
                const rules = get(field, 'params.component.config.rules');
                if (!rules || (Array.isArray(rules) && !rules.find(item => item.min || item.max))) {
                    fields = modifyConfig(
                        field.id,
                        {
                            rules: [
                                ...(rules || []),
                                {
                                    validator(_, value, callback) {
                                        if (value) {
                                            if (value.length < 2 || value.length > 50) {
                                                callback('2-50个字符！');
                                            } else {
                                                callback();
                                            }
                                        } else {
                                            callback();
                                        }
                                    }
                                }
                            ]
                        },
                        fields
                    );
                }
            }
        }
    });

    // 时长校验不能为 0
    const existsDuration = existField(fields, 'duration');
    if (existsDuration) {
        fields = modifyConfig(
            'duration',
            {
                rules: [
                    {
                        validator(_, value, callback) {
                            if (value === 0) {
                                callback('时长不能为 0！');
                            } else if (!value) {
                                callback('时长不能为空！');
                            } else {
                                callback();
                            }
                        }
                    }
                ]
            },
            fields
        );
    }
    // 增加时间的校验
    if (formType === applyType.TYPE_ON_SYSTEM) {
        fields = dateRange({
            fields,
            formType,
            form,
            country,
            startTimeName: 'startTime',
            endTimeName: 'endTime',
            unit: 1
        });
    } else {
        fields = dateRange({
            fields,
            formType,
            form,
            country,
            startTimeName: 'startTime',
            endTimeName: 'endTime',
            unit: country === 'sg' ? 2 : 3
        });
    }
    fields = dateRange({
        fields,
        formType,
        form,
        country,
        startTimeName: 'entryDate',
        endTimeName: 'entryDateEnd',
        disabled: false,
        unit: 1
    });
    fields = dateRange({
        fields,
        formType,
        form,
        country,
        startTimeName: 'contractBeginDate',
        endTimeName: 'contractBeginDateEnd',
        disabled: false,
        unit: 1
    });
    fields = dateRange({
        fields,
        formType,
        form,
        country,
        startTimeName: 'releaseTime',
        endTimeName: 'releaseTimeEnd',
        disabled: false,
        unit: 3
    });

    return {
        ...json,
        fields
    };
};

/**
 * （公用）处理表单域的change，非公用请到 dealFieldChange.js 里实现
 */
// export const initDealFieldChange = ({
//     id,
//     value,
//     form,
//     country,
//     setJson
// }) => {};

/**
 * 转换字典为 Select 的 Options
 * @param data
 * @param fields
 * @param setOther 是否要保留其他属性
 * @returns {Array|*}
 */
export const getOptionData = (data, fields, setOther = false) => {
    const { key, label } = fields;
    if (!data) return [];
    return (
        data &&
        data.map(item =>
            !setOther ? { key: item[key], label: item[label] } : { ...item, key: item[key], label: item[label] }
        )
    );
};
/**
 * 转换字典为 Radio 的 Options
 * @param data
 * @returns {Array|*}
 */
export const getRadioOptionData = (data, fields) => {
    const { key, label } = fields;
    if (!data) return [];
    return data.map(item => ({
        value: item[key],
        label: item[label]
    }));
};

/**
 * 根据国家和单位获取时间
 * @param name  开发或结束时间
 * @param type  国家
 * @param unit  单位
 * @param value 值
 * @returns {string|*}
 */
export const getFormatByUnit = (name, type, unit, value) => {
    if (!value) return '';
    if (type === 'zh') {
        if (unit === 1) {
            if (name === 'startTime') {
                return value.format('YYYY-MM-DD 09:00:00');
            }
            return value.format('YYYY-MM-DD 18:00:00');
        }
        return value.format('YYYY-MM-DD HH:mm:00');
    }
    if (type === 'sg') {
        return value.format('YYYY-MM-DD HH:mm:00');
    }
    return '';
};

/**
 * 根据 leaveCode 获取 leaveUnit
 * @param list
 * @param key
 * @returns {string|*}
 */
export const getLeaveUnit = (list, key) => {
    if (!list) return '';
    const find = list.find(item => item.leaveCode === key);

    if (find) {
        return find.leaveUnit;
    }
    return '';
};

/**
 * 获取字典
 * @param fields
 * @param code
 * @param name
 * @param isRadio
 * @returns {Promise<*>}
 */
export const getDict = async (fields, code, name, isRadio = false, callback = false) => {
    const result = await dictionaryList({
        code
    });

    if (result.code === 10000) {
        const data = !isRadio
            ? getOptionData(result.data || [], { key: 'dictValue', label: 'dictName' })
            : getRadioOptionData(result.data || [], { key: 'dictValue', label: 'dictName' });
        // eslint-disable-next-line no-unused-expressions
        callback && callback(result.data);
        return modifyProps(
            name,
            {
                options: data
            },
            fields
        );
    }
    return fields;
};

export const renderDict = (fields, name, data, isRadio = false, callback = false, propertyName = 'options') => {
    const tmpData = !isRadio
        ? getOptionData(data || [], { key: 'dictValue', label: 'dictName' })
        : getRadioOptionData(data || [], { key: 'dictValue', label: 'dictName' });
    // eslint-disable-next-line no-unused-expressions
    callback && callback(data);
    return modifyProps(
        name,
        {
            [propertyName]: tmpData
        },
        fields
    );
};

export const onNewsPreview = ({ form }) => {
    form.validateFieldsAndScroll(async (err, values) => {
        if (!err) {
            console.info('values:', values);
            const {
                createTime,
                labelCn,
                labelEn,
                newsCnContent,
                newsCnName,
                newsEnContent,
                newsEnName,
                newsType,
                releaseTime,
                attachmentNews,
                attachmentRec
            } = values;

            const data = {
                createTime,
                labelCn,
                labelEn,
                newsCnContent: newsCnContent.toHTML(),
                newsCnName,
                newsEnContent: newsEnContent.toHTML(),
                newsEnName,
                newsTypes: newsType,
                releaseTime: releaseTime.time.format('YYYY-MM-DD HH:mm:00'),
                resourceRelation: [attachmentNews.uploadResourceFile, attachmentRec.uploadResourceFile]
            };
            const response = await request('/api/officialwebsite/v1/news/insert', {
                method: 'POST',
                data
            });

            if (response.code === 10000) {
                console.info('result:', response.data);
                // TODO 带 id 跳转到官网
                // history.push(`/personal/portal/flow/min/list/test?newsKye=${response.data.id}`);
                window.open(`https://www.vv.cn/detail/?hash=${response.data.id}`);
            }
        }
    });
};
